/*
 * @Descripttion:
 * @version:
 * @Author: 夜殇
 * @Date: 2020-03-08 14:17:01
 * @LastEditors: 夜殇
 * @LastEditTime: 2020-06-11 17:29:30
 */

const express = require('express')
const mongoose = require('mongoose')
const bodyParser = require('body-parser')
const path = require('path')
const passport = require('passport')
const app = express()
const expressWs = require('express-ws')(app)

const { port, mongodbURI } = require('./config/key')

const user = require('./routers/api/user')
const course = require('./routers/api/course')
const student = require('./routers/api/student')
const teacher = require('./routers/api/teacher')

app.use('public', express.static(path.join(__dirname, './public')))
app.use('views', express.static(path.join(__dirname, './views')))

// 配置body-parser
app.use(
  bodyParser.urlencoded({
    extended: false
  })
)
app.use(bodyParser.json())

// passport init
app.use(passport.initialize())
require('./config/passport')(passport)

// 连接mongodb数据库
mongoose
  .connect(mongodbURI, {
    useNewUrlParser: true
  })
  .then(() => {
    console.log('mongodb is connect')
  })
  .catch(error => {
    console.log(error)
  })
mongoose.set('useFindAndModify', false)

app.all('*', (req, res, next) => {
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE')
  res.header('Content-Type', 'application/json;charset=utf-8')
  next()
})

// 路由配置
app.use('/api/user', user)
app.use('/api/course', course)
app.use('/api/student', student)
app.use('/api/teacher', teacher)

const User = require('./models/User')

// 创建websocket服务
app.ws('/chat', (ws, req) => {
  ws.on('message', res => {
    const data = JSON.parse(res)
    User.findById(data.id).then(user => {
      if (typeof data.chatMsg === 'string') {
        expressWs.getWss().clients.forEach(item => {
          item.send(
            JSON.stringify({
              id: data.id,
              nickName: user.nickName,
              avatar: user.avatar,
              chatMsg: data.chatMsg
            })
          )
        })
      }
    })
  })

  ws.on('error', err => {
    console.log(err)
  })
})

app.listen(port, () => {
  console.log(`the port is running in ${port}`)
})
